using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace AdRotator.Networking
{
    internal class AdWebRequest
    {
        public async static Task<List<AdWebResponse>> ReadInnerActiveAdResponse(string rssUrl)
        {
            var results = await Network.GetStringFromURL(rssUrl);
            if (string.IsNullOrEmpty(results))
            {
                return null;
            }
            results = results.Replace("tns:", "");

            var xdoc = XDocument.Parse(results);
            var AdError = xdoc.Root.Attribute("Error").Value;
            var AdClientID = xdoc.Root.Element("Client").FirstAttribute.Value;
            List<AdWebResponse> AdWebResponse = (from item in xdoc.Descendants("Ad")
                                                 select new AdWebResponse()
                                                 {
                                                     Error = AdError,
                                                     ClientID = AdClientID,
                                                     Text = item.IfNullEmptyString("Text"),
                                                     URL = item.IfNullEmptyString("URL"),
                                                     ImageURL = item.IfNullEmptyString("Image")
                                                 }).ToList();
            return AdWebResponse;
        }

        public async static Task<List<AdWebResponse>> ReadMobFoxAdResponse(string rssUrl)
        {
            var results = await Network.GetStringFromURL(rssUrl);
            if (string.IsNullOrEmpty(results) || results.Contains("<error>") || results.Contains("<request type=\"noAd\">"))
            {
                return null;
            }

            var xdoc = XDocument.Parse(results);

            List<AdWebResponse> AdWebResponse = (from item in xdoc.Descendants("request")
                                                 select new AdWebResponse()
                                                 {
                                                     URL = item.IfNullEmptyString("clickurl"),
                                                     ImageURL = string.IsNullOrEmpty(item.IfNullEmptyString("imageurl")) ? item.ifNullHTMLImageSource("htmlString") : item.IfNullEmptyString("imageurl")
                                                 }).ToList();

            return AdWebResponse;
        }
    }
}
